<!--
 * @Author: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Date: 2022-05-28 09:48:37
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @LastEditTime: 2022-08-22 10:36:49
 * @FilePath: \energy-om-platform\src\views\cabint\log.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="cmds">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <div class="tipstext">
        <el-alert
          :closable="false"
          :title="`${equipLabel}编码格式：多个编码之间以英文半角','拼接，禁止输入特殊字符！例如：CC08DPC0202204250001,CC08DPC0202205070001,0000092011500063`"
          type="error"
        >
        </el-alert>
      </div>
      <el-form-item :label="`${equipLabel}编码`" prop="codes">
        <el-input
          type="textarea"
          :rows="8"
          :placeholder="`请输入${equipLabel}编码，多个编码之间以半角','拼接`"
          v-model.trim="form.codes"
          @change.native="keyUp($event, index)"
          @input.native="keyInput($event, index)"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="选择软件版本" prop="softwareVersionId">
        <el-select
          v-model="form.softwareVersionId"
          placeholder="请选择软件版本"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in softList"
            :key="index"
            :label="item.filename"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="升级类型" prop="softwareUpgradeType">
        <el-select
          v-model="form.softwareUpgradeType"
          placeholder="请选择升级类型"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in enums.SOFTWARE_UPGRADE_TYPE"
            :key="index"
            :label="item.label"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="dialog-footer">
        <el-button @click="resetForm('form')">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm('form')"
          :loading="btnLoading"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import { equip, softversion } from "@/api/cabint";
export default {
  props: {
    updateDialogVisible: {
      default: true,
      type: Boolean,
    },
    // 设备类型
    equipType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        equipmentType: this.equipType,
        softwareVersionId: "", //软件版本id
        codes: "", //设备Code
        softwareUpgradeType: "", //升级类型
      },
      rules: {
        codes: [{ required: true, message: "请输入编码", trigger: "blur" }],
        softwareVersionId: [
          { required: true, message: "请选择软件版本", trigger: "change" },
        ],
        softwareUpgradeType: [
          { required: true, message: "请选择升级类型", trigger: "change" },
        ],
      },
      btnLoading: false, //按钮loading
      equipLabel: "", //编码label
      softList: [],
    };
  },
  computed: {
    ...mapGetters(["enums"]),
  },
  watch: {
    updateDialogVisible: {
      handler(newVal, oldVal) {
        if (!newVal) {
          this.resetData();
        }
      },
      immediate: true,
    },
    equipType: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getSoftList();
        }
      },
      immediate: true,
    },
  },
  created() {
    this.equipLabel =
      this.equipType == "CHARGING_CABINET" ? "充电柜" : "换电柜";
  },

  methods: {
    //限制输入特殊字符
    keyUp(e) {
      let str = e.target.value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
      e.target.value = str;
      this.form.codes = str;
    },
    // 只能输入汉字、英文、数字
    keyInput(e) {
      let str = e.target.value.replace(/[^\a-\z\A-\Z0-9,\n/]/g, "");
      e.target.value = str;
      this.form.codes = str;
    },
    // 获取软件版本集合
    async getSoftList() {
      let res = await softversion({ equipmentType: this.equipType });
      this.softList = res.data;
    },
    resetData() {
      this.resetForm("form");
      this.btnLoading = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isDoLog();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.form = {
        equipmentType: this.equipType,
        softwareVersionId: "", //软件版本id
        codes: "", //设备Code
        softwareUpgradeType: "",
      };
      this.emitClose();
    },
    // 通知关闭弹框
    emitClose() {
      this.$emit("closeDialog");
    },

    async doLog() {
      this.btnLoading = true;
      let params = { ...this.form };

      let flits = params.codes.split(",").join(",");
      let codes = flits.includes("\n") ? flits.replace(/[\r\n]/g, "") : flits;
      params.codes = codes.endsWith(",")
        ? codes.substr(0, codes.length - 1)
        : codes;

      await equip("/batch/insert_upgrade", "post", params, 2)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.emitClose();
            this.$emit("resetData");
          }
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
    isDoLog() {
      this.$confirm("是否确认要导入并升级吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.doLog();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
  margin-top: 100px;
}
.tipstext {
  margin: 0 0 30px 110px;
}
</style>
